# == Schema Information
#
# Table name: posts
#
#  id         :integer          not null, primary key
#  order_num  :integer
#  plate_id   :integer          default("news")
#  status     :integer          default("unpublished")
#  title      :string(255)
#  content    :text(65535)
#  cover_src  :string(255)
#  cover_link :string(255)
#  file_name  :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Post < ApplicationRecord
  require 'carrierwave/orm/activerecord'

  default_scope {order('order_num asc')}

  validates_presence_of :plate_id, :title, :content

  after_save :reorder?
  after_destroy :reorder

  mount_uploader :cover_src, AttachmentUploader
  mount_uploader :file_name, AttachmentUploader

  PLATE_ID = {news: 1, immigration_project: 2, after_service: 3, about_ireland: 4, about_keane: 5, about_us: 6, partner: 7}
  STATUS = {unpublished: 0, published: 1}

  extend Enumerize
  enumerize :plate_id, :in => PLATE_ID, predicates: {prefix: true}, scope: true
  enumerize :status, :in => STATUS, predicates: {prefix: true}, scope: true

  scope :active_posts, -> {where(status: 1)}

  private

  def reorder?
    reorder if self.saved_change_to_order_num? || self.order_num.blank?
  end

  def reorder
    Post.where(order_num: self.order_num, plate_id: self.plate_id_value).where("id != #{self.id}").first.try(:update_column, :order_num, self.order_num_before_last_save)
    Post.where(plate_id: self.plate_id_value).order('order_num asc').each_with_index do |c, index|
      c.update_column(:order_num, index + 1)
    end
  end

end
